<template>
  <div class="nickname">
    <navBar
      :title="str[type]"
      path="/home/myInfo"
      :right="right"
      @rightClick="save"
    ></navBar>
    <div class="content">
      <van-field v-model="inputValue" class="inp" v-if="type !== 'avatar'" />
      <van-uploader
        v-else
        :before-read="beforeRead"
        v-model="imgArr"
        :after-read="afterRead"
        max-count="1"
        @delete="delImag"
      ></van-uploader>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { auEdit, upload } from '@/api/my.js'
export default {
  data () {
    return {
      inputValue: '',
      right: '',
      type: this.$route.query.type,
      str: {
        nickname: '修改昵称',
        intro: '修改个人简介',
        avatar: '修改头像',
        position: '修改岗位'
      },
      imgArr: []
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  watch: {
    inputValue (newValue) {
      if (newValue !== '' && newValue !== this.userInfo[this.type]) {
        this.right = '保存'
      } else {
        this.right = ''
      }
    }
  },
  created () {
    this.inputValue = this.userInfo[this.type]
    if (this.type === 'avatar' && this.userInfo.avatar) {
      this.imgArr = [
        {
          url: this.$baseUrl + this.userInfo.avatar
        }
      ]
    }
  },
  methods: {
    async save () {
      this.$toast.loading('保存中...')
      await auEdit({ [this.type]: this.inputValue })
      this.$toast.success('保存成功')
      if (this.type === 'position') {
        this.$router.push('/home/my')
      } else {
        this.$router.push('/home/myInfo')
      }
      // 调用接口，将最新的数据渲染出来
      this.$store.dispatch('refreshUserInfo')
    },
    beforeRead (file) {
      const _type = file.type === 'image/png' || file.type === 'image/jpeg'
      const _size = file.size / 1024 / 1024 < 2
      if (!_type) {
        this.$toast.fail('请选择PNG或者JPG格式图片~')
      }
      if (!_size) {
        this.$toast.fail('图片大小不能超过2M')
      }
      return _type && _size
    },
    async afterRead (res) {
      const _formData = new FormData()
      _formData.append('files', res.file)
      const res2 = await upload(_formData)
      this.inputValue = res2.data.data[0].id
    },
    delImag () {
      console.log(11)
      this.inputValue = ''
    }
  }
  // 需求：更改了内容才显示保存，内容为空不显示保存
}
</script>

<style lang="less" scoped>
.nickname {
  .content {
    padding: @p15;
    .inp {
      background-color: #ccc;
    }
  }
}
</style>
